var config = require('../config.js')
function getExtConfig(cb){
  if (wx.getExtConfig) {
	  wx.getExtConfig({
		success: function (res) {
			if(res.extConfig){
			  typeof cb == "function" && cb(res.extConfig);
			}
		}
	  })
  }
}
function getUserInfo(cb){
	try {
	  var userInfo = wx.getStorageSync('userInfo');
	  typeof cb == "function" && cb(userInfo);
	} catch (e) {
	  console.log(e);
	}
	
}
function extend() {
	var o={};
	var i =0,len=arguments.length;
	for(;i<len;i++){
		var source = arguments[i];
		for(var prop in source){
			o[prop] = source[prop];
		}
	}
	return o;
}

function request(url,data,success, timeout = 3600, cacheKey = "", delKey = []) {
  let key = cacheKey != "" ? cacheKey : url;
  url = 'https://shop.bidcms.com/app.php?r=' + url;
  if (url.substr(0, 4) == 'http') {
    url = url;
  }
  if (delKey.length > 0) {
    for (var i in delKey) {
      wx.removeStorageSync(delKey[i]);
    }

  }
  var res = key != '' ? wx.getStorageSync(key) : null;
  if (res != null && res.data && timeout > 0) {
    if (new Date().getTime() - res.ctime >= timeout * 1000) {
      wx.removeStorageSync(key);
    }
    success(res);
  } else {
    wrequest(url, data).then((res) => {
      var pass = Object.keys(res.data).length>0 && (Object.keys(res.data.data).length > 0 || res.data.data.length>0);
      if (timeout >= 0 && key != "" && pass && res.data.code == 0) {
        wx.setStorageSync(key, { "data": res.data, "ctime": new Date().getTime() });
      }
      success(res);
    })
  }

}
/**
 * 微信的的request
 */
function wrequest(url, data = {}, method = "POST") {
  return new Promise(function (resolve, reject) {
    getExtConfig(function (extConfig) {
      let datas = {}
      datas.pid = extConfig.pid;
      datas.appid = extConfig.appid;
      datas.version = extConfig.version;
      let token = wx.getStorageSync('token');
      if (token && !data.token) {
        datas.token = token;
      }
      datas = extend(datas, data);
      wx.request({
        url: url,
        data: datas,
        method: method,
        header: {
          'Content-Type': 'application/json',
          'X-Nideshop-Token': wx.getStorageSync('token')
        },
        success: function (res) {
          if (res.statusCode == 200) {
            resolve(res);
          } else {
            reject(res.statusCode);
          }

        },
        fail: function (err) {
          reject(err)
          console.log("failed")
        }
      })
    });

  });
}

function Upload (url ,file ,data, cb ){
  if (url.substring(0, 4).toLowerCase()!='http') {
    url = config.HTTP_BASE_URL + url;
  }
  url = url.replace('http://', 'https://');
	wx.uploadFile({
		url:  url,
		filePath: file,
		name:"file",
		formData:data,
		success: (res) => {
			if( typeof(res.data)=="string"  ){
				typeof cb == "function" && cb( JSON.parse(res.data),"");
			}else{
				typeof cb == "function" && cb(res.data,"");	
			}
			
		},
		fail:(err) => {
			typeof cb == "function" && cb(null,err.errMsg);
		}
	});
};


/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      success: function (res) {
        resolve(res);
      },
      fail: function (err) {
        reject(err);
      }
    })
  });
}

module.exports ={
  request: request,
  getUserInfo:getUserInfo,
  login:login,
  getExtConfig:getExtConfig,
  httpUpload:Upload
};